from flask import Flask, request
from flask_cors import CORS
from manager import StateManager
from dto import ApiResponseBuilder
from exception import register_global_exception_handlers
from logger.process_logger import process_logger
import logging
import os

app = Flask(__name__)

# 配置CORS
CORS(app, origins=['*'])

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 注册全局异常处理器
register_global_exception_handlers(app)

# 创建状态管理器实例
try:
    state_manager = StateManager()
    logger.info("状态管理器初始化成功")
except Exception as e:
    logger.error(f"状态管理器初始化失败: {str(e)}")
    raise


@app.route('/api/status', methods=['GET'])
def get_system_status():
    """获取系统整体状态和所有进程状态"""
    process_logger.log_api_request("GET /api/status")

    # 获取系统状态
    system_state = state_manager.get_system_state()

    # 获取所有进程状态
    processes_status = state_manager.get_all_processes_status()

    # 获取资源冲突信息
    resource_conflicts = state_manager.get_resource_conflicts_info()

    data = {
        'system_state': system_state,
        'processes': processes_status,
        'resource_conflicts': resource_conflicts
    }

    response = ApiResponseBuilder.success(data, "获取系统状态成功")
    return response.to_json_response()


@app.route('/api/config', methods=['GET'])
def get_config_info():
    """获取配置信息"""
    process_logger.log_api_request("GET /api/config")

    try:
        # 获取进程配置信息
        process_config = state_manager.get_process_config_info()

        # 获取资源配置信息
        resource_names = state_manager.resource_names
        exclusive_indices = state_manager.exclusive_indices

        data = {
            'processes': process_config,
            'resources': {
                'names': resource_names,
                'exclusive_indices': exclusive_indices,
                'resource_details': state_manager.config.resources
            },
            'system': state_manager.config.system
        }

        response = ApiResponseBuilder.success(data, "获取配置信息成功")
        return response.to_json_response()

    except Exception as e:
        logger.error(f"获取配置信息失败: {str(e)}")
        response = ApiResponseBuilder.internal_error(f"获取配置信息失败: {str(e)}")
        return response.to_json_response()


@app.route('/api/process/<name>/start', methods=['POST'])
def start_process(name):
    """启动指定进程"""
    process_logger.log_api_request(f"POST /api/process/{name}/start", name)

    success, message = state_manager.start_process(name)

    if success:
        logger.info(f"启动进程成功: {name}")
        response = ApiResponseBuilder.success(message=message)
    else:
        logger.warning(f"启动进程失败: {name} - {message}")
        response = ApiResponseBuilder.error(message)

    return response.to_json_response()


@app.route('/api/process/<name>/stop', methods=['POST'])
def stop_process(name):
    """停止指定进程"""
    process_logger.log_api_request(f"POST /api/process/{name}/stop", name)

    success, message = state_manager.stop_process(name)

    if success:
        logger.info(f"停止进程成功: {name}")
        response = ApiResponseBuilder.success(message=message)
    else:
        logger.warning(f"停止进程失败: {name} - {message}")
        response = ApiResponseBuilder.error(message)

    return response.to_json_response()


@app.route('/api/process/<name>/status', methods=['GET'])
def get_process_status(name):
    """获取单个进程状态"""
    process_state = state_manager.get_process_state(name)

    if process_state is None:
        response = ApiResponseBuilder.not_found(f"进程 {name}")
        return response.to_json_response()

    # 获取详细状态信息
    all_status = state_manager.get_all_processes_status()
    process_info = all_status.get(name, {})

    data = {
        'name': name,
        'state': process_state.value,
        'resources': process_info.get('resources', []),
        'pid': process_info.get('pid'),
        'display_name': process_info.get('display_name', name),
        'description': process_info.get('description', '')
    }

    response = ApiResponseBuilder.success(data, f"获取进程 {name} 状态成功")
    return response.to_json_response()


@app.route('/api/system/reset', methods=['POST'])
def reset_system():
    """停止所有进程"""
    process_logger.log_api_request("POST /api/system/reset")

    results = []
    stopped_processes = []
    all_processes = state_manager.get_all_processes_status()

    for name, info in all_processes.items():
        if info['state'] == 'running':
            success, message = state_manager.stop_process(name)
            results.append({
                'process': name,
                'success': success,
                'message': message
            })
            if success:
                stopped_processes.append(name)

    # 记录系统重置
    process_logger.log_system_reset(stopped_processes)

    logger.info("系统重置完成")
    response = ApiResponseBuilder.success(
        data={'results': results},
        message='系统重置完成'
    )
    return response.to_json_response()


@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    process_logger.log_api_request("GET /api/health")

    try:
        health_status = state_manager.check_all_processes_health()

        # 找出不健康的进程
        unhealthy_processes = [
            name for name, (is_healthy, _) in health_status.items()
            if not is_healthy
        ]

        # 记录健康检查结果
        process_logger.log_health_check(unhealthy_processes)

        # 统计健康状态
        total_processes = len(health_status)
        healthy_count = sum(1 for is_healthy, _ in health_status.values() if is_healthy)

        data = {
            'total_processes': total_processes,
            'healthy_processes': healthy_count,
            'unhealthy_processes': total_processes - healthy_count,
            'process_health': {name: {'healthy': status[0], 'message': status[1]}
                               for name, status in health_status.items()}
        }

        response = ApiResponseBuilder.success(data, "健康检查完成")
        return response.to_json_response()

    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        response = ApiResponseBuilder.internal_error(f"健康检查失败: {str(e)}")
        return response.to_json_response()


@app.route('/api/logs', methods=['GET'])
def get_process_logs():
    """获取进程管理日志"""
    try:
        lines = int(request.args.get('lines', 100))  # 默认100行

        log_file = "logs/process_manager.log"

        if not os.path.exists(log_file):
            response = ApiResponseBuilder.success(
                data={"logs": "", "total_lines": 0},
                message="日志文件不存在"
            )
            return response.to_json_response()

        with open(log_file, "r", encoding="utf-8") as f:
            all_lines = f.readlines()
            tail_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines
            logs = "".join(tail_lines)

        response = ApiResponseBuilder.success(
            data={
                "logs": logs,
                "total_lines": len(all_lines),
                "showing_lines": len(tail_lines)
            },
            message=f"获取最后{len(tail_lines)}行日志成功"
        )
        return response.to_json_response()

    except Exception as e:
        logger.error(f"获取日志失败: {str(e)}")
        response = ApiResponseBuilder.internal_error(f"获取日志失败: {str(e)}")
        return response.to_json_response()


@app.route('/api/logs/clear', methods=['POST'])
def clear_process_logs():
    """清空进程管理日志"""
    try:
        log_file = "logs/process_manager.log"

        if os.path.exists(log_file):
            with open(log_file, "w", encoding="utf-8") as f:
                f.write("")

        process_logger.log_api_request("POST /api/logs/clear")

        response = ApiResponseBuilder.success(message="日志清空成功")
        return response.to_json_response()

    except Exception as e:
        logger.error(f"清空日志失败: {str(e)}")
        response = ApiResponseBuilder.internal_error(f"清空日志失败: {str(e)}")
        return response.to_json_response()


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=5000)